//
//  HMNetworkTools.swift
//  16、swift中网络请求的封装
//
//  Created by 朱建超 on 16/11/15.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethod {
    case GET
    case POST
}

class HMNetworkTools: AFHTTPSessionManager {

    //声明单例对象
    static let shared : HMNetworkTools = {
    
        let tools = HMNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    
    }()

    //声明封装的函数
    /*
     1、请求的方法
     2、urlString
     3、参数
     4、请求的回调
        -成功
        -失败
     */
    
    func request(method : HTTPMethod , urlString : String , parameters : Any? , finished : @escaping (Any? , Error?) -> ()) {
        
        let successCallBack = { (task : URLSessionDataTask? , responseObject : Any?) -> () in
            
            //执行成功的回调
            finished(responseObject,nil)
            
        }
        
        let failureCallBack = { (task : URLSessionDataTask? , error : Error) -> () in
            
            //执行失败的回调
            finished(nil,error)
            print(error)
            
        }
        
        if method == .GET {
            self.get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else{
        
            self.post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        
        }
        
    }
    
    
}
